<template>
  <CommonPage>
    <template #action>
      <n-button v-permission="'AddUser'" type="primary" @click="handleAdd()">
        <i class="i-material-symbols:add mr-4 text-18" />
        创建新用户
      </n-button>
    </template>

    <MeCrud ref="$table" v-model:query-items="queryItems" :scroll-x="1200" :columns="columnFields" :get-data="api.read">
      <MeQueryItem label="用户名" :label-width="50">
        <n-input v-model:value="queryItems.userName" type="text" placeholder="请输入用户名" clearable />
      </MeQueryItem>

      <MeQueryItem label="审核状态" :label-width="80">
        <n-select v-model:value="queryItems.status" clearable label-field="name" value-field="id"
          :options="statusOptions" />
      </MeQueryItem>

      <!-- <MeQueryItem label="用户类型" :label-width="80">
        <n-select v-model:value="queryItems.userType" clearable label-field="name" value-field="id"
          :options="typeOptions" />
      </MeQueryItem> -->
    </MeCrud>

    <MeModal ref="modalRef" width="880px">
      <n-form ref="modalFormRef" label-placement="left" label-align="right" :model="modalForm"
        :disabled="modalAction === 'view'">
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi v-for="field in formFields" :key="field.key" :span="12" :label="field.title"
            :disabled="modalAction !== 'add'" label-width="140px">
            <n-select v-if="field.options?.length > 0" v-model:value="modalForm[field.key]" :options="field.options"
              label-field="name" value-field="id" clearable filterable />
            <n-upload v-else-if="field.isImage" :action="`/api/upload`" list-type="image-card" :max="1"
              :multiple="false" :default-file-list="modalAction === 'view' ? [
                  {
                    id: modalForm[field.key],
                    name: modalForm[field.key],
                    url: modalForm[field.key],
                    status: 'finished',
                  },
                ] : []
                " @finish="(e) => onFinish(e, field.key)">
              点击上传
            </n-upload>
            <n-input v-else v-model:value="modalForm[field.key]" />
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </MeModal>
  </CommonPage>
</template>

<script setup>
import { NButton } from 'naive-ui'
// import { formatDateTime } from '@/utils'
import { MeCrud, MeQueryItem, MeModal } from '@/components'
import { useCrud } from '@/composables'
import api, { genColumns, statusOptions, typeOptions } from './api'

defineOptions({ name: 'UserMgt' })

const $table = ref(null)
/** QueryBar筛选参数（可选） */
const queryItems = ref({})

onMounted(() => {
  $table.value?.handleSearch()
})

const tempColumns = genColumns({})
const initForm = tempColumns
  .filter((i) => i.isForm)
  .reduce((pre, cur) => {
    pre[cur.key] = cur.options ? undefined : ''
    return pre
  }, {})

const {
  modalRef,
  modalFormRef,
  modalForm,
  modalAction,
  handleAdd,
  handleDelete,
  handleOpen,
  handleSave,
} = useCrud({
  name: '用户',
  initForm,
  doCreate: api.create,
  doDelete: api.delete,
  doUpdate: api.update,
  refresh: () => $table.value?.handleSearch(),
})

function onFinish({ event }, key) {
  const result = JSON.parse(event.target.response)
  modalForm.value[key] = result.data.imgUrl
}

// async function handleEnable(row) {
//   row.enableLoading = true
//   try {
//     await api.update({ id: row.id, enable: !row.enable })
//     row.enableLoading = false
//     $message.success('操作成功')
//     $table.value?.handleSearch()
//   } catch (error) {
//     row.enableLoading = false
//   }
// }

function handleOpenRolesSet(row) {
  const roleIds = [] || row.roles.map((item) => item.id)
  handleOpen({
    action: 'setRole',
    title: '设置审核状态',
    row,
    onOk: onSave,
  })
}

function onSave() {
  if (modalAction.value === 'setRole') {
    return handleSave({
      api: () => api.update(modalForm.value),
      cb: () => $message.success('设置成功'),
    })
  } else if (modalAction.value === 'reset') {
    return handleSave({
      api: () => api.resetPwd(modalForm.value.id, modalForm.value),
      cb: () => $message.success('密码重置成功'),
    })
  }
  handleSave()
}

const columns = genColumns({ handleOpenRolesSet, handleOpen, handleDelete, onSave, h })

const columnFields = computed(() => columns.filter((col) => col.isTable))
const formFields = computed(() =>
  columns.filter((col) =>
    modalAction.value === 'setRole'
      ? col.isSetRole
      : modalAction.value === 'reset'
        ? col.isResetPwd
        : col.isForm
  )
)
</script>
